import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:get/get.dart';
import 'package:ball_lion/service/config_service.dart';
import 'package:ball_lion/entity/other/app_update_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/update_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';

import 'base/wqs_text.dart';

class UpdateCheckSheet extends StatefulWidget {
  const UpdateCheckSheet({super.key});

  @override
  State<UpdateCheckSheet> createState() => _UpdateCheckSheetState();
}

class _UpdateCheckSheetState extends State<UpdateCheckSheet> {
  AppUpdateEntity? get updateInfo => UpdateUtils.updateInfo;
  String? get version => UpdateUtils.packageInfo?.version;
  bool updateClicked = false;

  @override
  initState() {
    Get.find<ConfigService>().tipEnable = false;
    super.initState();
  }

  @override
  dispose() {
    Get.find<ConfigService>().tipEnable = true;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
        canPop: false,
        child: BottomSheet(
            onClosing: () {},
            clipBehavior: Clip.none,
            backgroundColor: Colours.transparent,
            builder: (context) => Container(
                  decoration: const BoxDecoration(
                      color: Colours.white,
                      borderRadius:
                          BorderRadius.vertical(top: Radius.circular(8))),
                  child: Stack(
                    clipBehavior: Clip.none,
                    alignment: Alignment.topCenter,
                    children: [
                      Image.asset(Utils.getImgPath("update_back.png"),
                          width: Get.width),
                      Positioned(
                        left: 16,
                        top: 0,
                        child: Container(
                          height: 40,
                          alignment: Alignment.bottomLeft,
                          child: updateInfo?.getForce == true
                              ? Container()
                              : Image.asset(Utils.getImgPath("close.png"),
                                      width: 24, height: 24)
                                  .tap(Get.back),
                        ),
                      ),
                      Container(
                          padding: const EdgeInsets.symmetric(horizontal: 20),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              SizedOverflowBox(
                                  size: const Size(0, 100),
                                  alignment: Alignment.bottomCenter,
                                  child: Image.asset(
                                      Utils.getImgPath('update_rocket.png'),
                                      width: 120,
                                      height: 120)),
                              Container(height: 8),
                              QsText("发现新版本 ${updateInfo?.latestVersion ?? ""}",
                                  color: Colours.text,
                                  fontSize: 18,
                                  fontWeight: FontWeight.w500),
                              const SizedBox(height: 8),
                              Container(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 6, vertical: 2),
                                decoration: BoxDecoration(
                                    color: Colours.main1,
                                    borderRadius: BorderRadius.circular(10)),
                                child: QsText("当前版本v$version",
                                    color: Colours.grey66, fontSize: 10),
                              ),
                              const SizedBox(height: 16),
                              SizedBox(
                                  height: 84,
                                  child: SingleChildScrollView(
                                    child: Html(
                                      data: updateInfo?.updateDesc,
                                      style: {
                                        "body": Style(
                                            padding: HtmlPaddings.zero,
                                            margin: Margins.zero),
                                        "p": Style(
                                          lineHeight: const LineHeight(1.4),
                                          margin: Margins.only(bottom: 2),
                                          color: Colours.grey66,
                                          fontSize: FontSize(14),
                                        )
                                      },
                                    ),
                                  )),
                              const SizedBox(height: 20),
                              _updateRow(),
                              const SizedBox(height: 20)
                            ],
                          )),
                    ],
                  ),
                )));
  }

  Widget _updateButton() {
    String title = "立即下载";
    if (SpUtils.apkPath.hasValue) {
      title = "已下载，立即安装";
    }
    return GestureDetector(
      onTap: () async {
        Utils.onEvent('sjtk', params: {'sjtk': '0'});
        int result = await UpdateUtils.update();
        if (result == 0 || result == 2) {
          Get.back();
        } else if (result == 1) {
          setState(() => title = "立即下载");
        }
      },
      child: Container(
        clipBehavior: Clip.hardEdge,
        decoration: BoxDecoration(
            color: Colours.main, borderRadius: BorderRadius.circular(24)),
        child: QsText(title,
                fontSize: 16, color: Colours.white, fontWeight: FontWeight.w500)
            .center,
      ),
    );
  }

  _updateRow() {
    return SizedBox(
      height: 48,
      child: Row(
        children: [
          if (updateInfo?.getForce == true) ...[
            Expanded(
              child: GestureDetector(
                onTap: () {
                  Utils.onEvent('sjtk', params: {'sjtk': '1'});
                  exit(0);
                },
                child: Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(24),
                      border: Border.all(
                          width: 1,
                          color: Colours.main,
                          style: BorderStyle.solid)),
                  child:
                      const QsText("退出应用", color: Colours.main, fontSize: 16),
                ),
              ),
            ),
            const SizedBox(width: 16),
          ],
          Expanded(child: _updateButton()),
        ],
      ),
    );
  }
}
